package com.fakeDYChat.common.user.service.adapter;

import com.fakeDYChat.common.common.domain.enums.YesOrNoEnum;
import com.fakeDYChat.common.user.domain.entity.ItemConfig;
import com.fakeDYChat.common.user.domain.entity.User;
import com.fakeDYChat.common.user.domain.entity.UserBackpack;
import com.fakeDYChat.common.user.domain.vo.resp.BadgeResp;
import com.fakeDYChat.common.user.domain.vo.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.beans.BeanUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class UserAdapter {
    public static User buildRegisterUser(String openId) {
        return User.builder().openId(openId).build();
    }

    public static User buildFillInfoUser(WxOAuth2UserInfo userInfo) {
        return User.builder()
                .openId(userInfo.getOpenid())
                .name(userInfo.getNickname())
                .avatar(userInfo.getHeadImgUrl())
                .build();
    }

    public static UserInfoResp buildUserInfo(User user, Integer modifyCount) {
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtils.copyProperties(user, userInfoResp);
        userInfoResp.setModifyNameChance(modifyCount);
        return userInfoResp;
    }

    public static List<BadgeResp> buildBadgeResp(List<ItemConfig> allBadges, List<UserBackpack> userOwnByItemIds, User user) {
        Set<Long> obtainItemSet = userOwnByItemIds.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        return allBadges.stream().map(i -> {
            BadgeResp badgeResp = new BadgeResp();
            BeanUtils.copyProperties(i, badgeResp);
            badgeResp.setObtain(obtainItemSet.contains(i.getId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            badgeResp.setWearing(Objects.equals(user.getItemId(), i.getId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing, Comparator.reverseOrder())
                .thenComparing(BadgeResp::getObtain, Comparator.reverseOrder())).collect(Collectors.toList());
    }
}
